package org.micro.rbac.core.valid.validator;


import cn.hutool.core.date.DateUtil;
import com.google.common.collect.Lists;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import org.micro.rbac.core.valid.DateTime;

import java.util.List;

/**
 * @author hongsir
 * @apiNote 摘要:自定义校验日期格式
 * @since 2019-05-29 08:53
 */
public class DateTimeValidator implements ConstraintValidator<DateTime, String> {

    private DateTime dateTime;

    @Override
    public void initialize(DateTime dateTime) {
        this.dateTime = dateTime;
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        // 如果 value 为空则不进行格式验证，为空验证可以使用 @NotBlank @NotNull @NotEmpty 等注解来进行控制，职责分离
        if (value == null || "".equals(value)) {
            return true;
        }
        String[] format = dateTime.format();
        List<Boolean> list = Lists.newArrayList();
        List<Boolean> length = Lists.newArrayList();
        for (String fm : format) {
            length.add(fm.length() == value.length());
            try {
                DateUtil.parse(value, fm);
                list.add(true);
            } catch (Exception e) {
                list.add(false);
            }
        }
        return list.contains(true) && length.contains(true);
    }

}
